﻿using System;
using MC.Warehouse.Views;
using System.Threading;

namespace MC.Warehouse.Core
{
    internal class WaitingProcess
    {
        private static int _amountItemInPool;
        private static Thread _workingThread;
        private static SplashScreenView _workingProcessView;

        public static bool IsWorking
        {
            get;
            private set;
        }

        internal static bool ActiveLastOpenForm
        {
            get;
            set;
        }

        public static int AmountItemInPool
        {
            get
            {
                return _amountItemInPool;
            }
            set
            {
                if (value < 0)
                {
                    return;
                }

                _amountItemInPool = value;

                if (value == 0 && IsWorking)
                {
                    CloseWorkingProcess();
                }
            }
        }

        public static void Show(int amountItemInPool)
        {
            if (!IsWorking && amountItemInPool > 0)
            {
                IsWorking = true;
                _workingProcessView = new SplashScreenView();

                _workingThread = new Thread(ShowWorkingProcess)
                {
                    IsBackground = true,
                };
                _workingThread.SetApartmentState(ApartmentState.STA);
                _workingThread.Start();
                Thread.Sleep(100);
            }
            AmountItemInPool = amountItemInPool;
        }

        private static void ShowWorkingProcess()
        {
            _workingProcessView.ShowDialog();
        }

        private static void CloseWorkingProcess()
        {
            if (_workingProcessView != null)
            {
                GC.ReRegisterForFinalize(_workingProcessView);
                try
                {
                    _workingProcessView.Close();
                }
                catch
                {
                    _workingThread.Abort();
                }
            }

            _workingThread = null;
            _workingProcessView = null;
            ActiveLastOpenForm = false;
            _amountItemInPool = 0;
            IsWorking = false;
        }

        public static void Close()
        {
            AmountItemInPool = 0;
        }

        public static void Show()
        {
            Show(++AmountItemInPool);
        }

    }
}
